// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <nebula/util/dict_util.h>
#include <nebula/array/array_dict.h>
#include <nebula/bits/bit_util.h>
#include <turbo/base/checked_cast.h>

namespace nebula {
namespace dict_util {

namespace {

template <typename IndexArrowType>
int64_t LogicalNullCount(const ArraySpan& span) {
  const auto* indices_null_bit_map = span.buffers[0].data;
  const auto& dictionary_span = span.dictionary();
  const auto* dictionary_null_bit_map = dictionary_span.buffers[0].data;

  using CType = typename IndexArrowType::c_type;
  const CType* indices_data = span.get_values<CType>(1);
  int64_t null_count = 0;
  for (int64_t i = 0; i < span.length; i++) {
    if (indices_null_bit_map != nullptr &&
        !bit_util::get_bit(indices_null_bit_map, i + span.offset)) {
      null_count++;
      continue;
    }

    CType current_index = indices_data[i];
    if (!bit_util::get_bit(dictionary_null_bit_map,
                          current_index + dictionary_span.offset)) {
      null_count++;
    }
  }
  return null_count;
}

}  // namespace

int64_t LogicalNullCount(const ArraySpan& span) {
  if (span.dictionary().get_null_count() == 0 || span.length == 0) {
    return span.get_null_count();
  }

  const auto& dict_array_type = turbo::checked_cast<const DictionaryType&>(*span.type);
  switch (dict_array_type.index_type()->id()) {
    case Type::UINT8:
      return LogicalNullCount<UInt8Type>(span);
    case Type::INT8:
      return LogicalNullCount<Int8Type>(span);
    case Type::UINT16:
      return LogicalNullCount<UInt16Type>(span);
    case Type::INT16:
      return LogicalNullCount<Int16Type>(span);
    case Type::UINT32:
      return LogicalNullCount<UInt32Type>(span);
    case Type::INT32:
      return LogicalNullCount<Int32Type>(span);
    case Type::UINT64:
      return LogicalNullCount<UInt64Type>(span);
    default:
      return LogicalNullCount<Int64Type>(span);
  }
}
}  // namespace dict_util
}  // namespace nebula
